import axios from 'axios'
import type { AxiosResponse, AxiosRequestHeaders } from 'axios'
import baseConfig from '@/config'
import { getToken } from '@/utils/auth'
import router from '@/router'
axios.defaults.baseURL = baseConfig.BASE_URL
axios.defaults.timeout = baseConfig.TIMEOUT

axios.interceptors.request.use(function (config) {
  (config.headers as AxiosRequestHeaders).Authorization = `Bearer ${getToken()}`
  // 在发送请求之前做些什么
  return config
},
function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
}
)

// 添加响应拦截器
axios.interceptors.response.use(
  function (response: AxiosResponse) {
    // 对响应数据做点什么
    return response.data
  },
  function (error) {
    // 对响应错误做点什么
    if(error.response.status == 401){
      router.push('/login')
    }


    error.response.data.message =
      error.response.data.msg || error.response.data.message;

    return Promise.reject(error.response?.data)
  }
)

export default axios
